/**
 ********************************************************************
 * @author roocket
 * @file    main.c
 * @version V0.0.0
 * @date    2024/3/22
 * @brief   This file is to indicate main functions. 
 * @attention Code file rules:
 * rule: file encoding use UTF8;
 * rule: max line length 120 characters;
 * rule: line separator \r\n;
 * rule: use clion auto code format tool.
 */

#include "sound.h"
#include "sound_wav_pcm.h"
#include "sound_decode_mp3.h"


int test_audio_cap_callbck(const char *buffer, int len)
{
    printf("the buffer len is %d\n", len);
    return 0;
}

void test_wav_to_pcm_file(void)
{
    sound_wav_to_pcm_format_file("test.wav", "test.pcm");
}

void test_mp3_to_pcm_file(void)
{
    struct sound_ffmpeg_player aplayer = {};
    int res;
    unsigned char buffer[20480 + AV_INPUT_BUFFER_PADDING_SIZE] = "";

    res = sound_ffmpeg_audio_player_init(&aplayer);
    if (-1 == res) {
        perror("sound ffmpeg audio player init error");
        return;
    }

    FILE *file = fopen("test.mp3", "rb");
    outfile = fopen("test.pcm","wb");

    while (1) {
        res = fread(buffer, 1, 20480, file);
        if (feof(file))
            break;
        sound_ffmpeg_audio_decode_mp3(&aplayer, buffer, res);
    }
    sound_ffmpeg_audio_player_deinit(&aplayer);
}

int main(void)
{
    int res = -1;
#if 0 // test code for user
    test_mp3_to_pcm_file();
    return 0;
#endif
    struct sound_alsa_player player = {};

    /* file */
    int fd = open("test.pcm", O_RDONLY);
    if (fd < 0) {
        perror("fopen error");
        return -1;
    }
    struct mixer_info mixer_info = {};
    sound_alsa_get_playback_volume("default", "Master", &mixer_info);
    mixer_info.left_val = 80;
    mixer_info.right_val = 80;

    sound_alsa_set_playback_volume("default", "Master", &mixer_info);

    player.snd_rate = 8000;
    player.snd_audio_format = SND_PCM_FORMAT_S16_LE;
    player.snd_pcm_stream_method = SND_PCM_STREAM_PLAYBACK;
    player.buffer_frame_cnt = 1024;
    player.snd_audio_channel = 1;

    res = sound_alsa_player_init("default", &player);
    if (-1 == res) {
        perror("sound alsa player init error");
        return -1;
    }
#if 0
    res = sound_alsa_capture_audio_data(&player, test_audio_cap_callbck);
    if (-1 == res) {
        perror("sound alsa capture audio data error");
        return -1;
    }
#endif
    char *buffer = (char *)malloc(player.psize_frames * 2);
    
    while (1) {
        int count = read(fd, buffer, player.psize_frames * 2);
        if (count <= 0)
            break;
        res = sound_alsa_playback_audio_data(&player, buffer);
        if (-1 == res)
            goto out;
    }
    sound_alsa_player_deinit(&player);
    return 0;

out:
    sound_alsa_player_deinit(&player);
    return -1;
}
